package com.open.capacity.db.service.impl;

import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.DB;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.db.dao.DBMapper;
import com.open.capacity.db.service.DBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class DBServiceImpl implements DBService {

    @Autowired(required = false)
    DBMapper dbMapper;

    public PageResult getDBList(Map map) {
        try {
            Integer page = Integer.valueOf((String) map.get("page")) - 1;
            Integer limit = Integer.valueOf((String) map.get("limit"));
            PageUtil.pageParamConver(map, true);
            map.put("page", page*limit);
            map.put("limit", limit);
            String param = (String) map.get("param");
            long count = dbMapper.getDBListCount(param);
            List<DB> list = Collections.emptyList();
            if (count > 0) {
                list = dbMapper.getDBList(map);
            }
            return PageResult.<DB>builder().data(list).code(0).count(count).build();
        } catch (ServiceException e) {
            throw new ServiceException(e);
        }

    }

    @Override
    public Result saveOrUpdate(DB db) {
        try {
            String url = db.getDbUrl();
            if (url.lastIndexOf("/") != -1)
                db.setDbName(url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")));
            else
                db.setDbName(url.substring(url.lastIndexOf("\\") + 1, url.lastIndexOf(".")));
            Integer i = 0;
            if (db.getDbId() == null) {
                i = dbMapper.saveDB(db);
            } else {
                i = dbMapper.updateDB(db);
            }
            return i > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
        } catch (ServiceException e) {
            throw new ServiceException(e);
        }

    }

    @Override
    public Result deleteDB(Integer dbId) {
        return dbMapper.deleteDB(dbId) > 0 ? Result.succeed("删除成功") : Result.failed("删除失败");
    }

}
